package com.ma.chapter8.executors;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @ClassName TestShutDown
 * @Author: mayongqiang
 * @DATE 2022/3/22 0:02
 * @Description: 关闭线程测试
 */
@Slf4j(topic = "m.TestShutDown")
public class TestShutDown {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService p = Executors.newFixedThreadPool(2);
        Future<Integer> result1 = p.submit(() -> {
            log.debug("task 1 running ... ");
            Thread.sleep(1000);
            log.debug("task 1 finish  ");
            return 1;
        });
        Future<Integer> result2 = p.submit(() -> {
            log.debug("task 2 running ... ");
            Thread.sleep(1000);
            log.debug("task 2 finish  ");
            return 2;
        });
        Future<Integer> result3 = p.submit(() -> {
            log.debug("task 3 running ... ");
            Thread.sleep(1000);
            log.debug("task 3 finish  ");
            return 3;
        });
        log.debug("shutdown");
        p.shutdown();  //不会取消之前的任务
        //最多等3秒/线程执行完     不能确定等多久 ，最好用 future.get() 进行阻塞等待结果

        //要进行某些回调时用它
        p.awaitTermination(3, TimeUnit.SECONDS);
        log.debug("other");

        //再提交会报异常
        //Future<Integer> result4= p.submit(() -> {
        //    log.debug("task 4 running ... ");
        //    Thread.sleep(1000);
        //    log.debug("task 4 finish  ");
        //    return 4;
        //});

    }
}
